<template>
  <div>
    <div v-if="allowInput" style="margin-bottom: 5px;">
      <el-input v-model="inputUrls" size="medium" v-on:input="rewriteToValue" :placeholder="`如果手动输入链接,请使用 ${actualSeparator} 分隔`"></el-input>
    </div>
    <el-upload
      ref="elUpload"
      list-type="picture-card"
      class="small-pic"
      :action="actualAction"
      :headers="actualHeaders"
      :on-preview="!onPreview ? defaultPreview : onPreview"
      :on-success="!onSuccess ? defaultSuccess : onSuccess"
      :on-remove="!onRemove ? defaultRemove : onRemove"
      :before-remove="!beforeRemove ? defaultBeforeRemove : beforeRemove"
      multiple
      :limit="limit"
      :on-exceed="!onExceed ? defaultExceed : onExceed"
      :file-list="fileList">
      <i class="el-icon-plus"></i>
    </el-upload>

  </div>

</template>

<script>
export default {
  name: 'el-multi-upload',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {

    // 头部
    headers: {
      type: Object
    },

    uploadDirectory: {
      type: String,
      default: '/cms/multiUpload'
    },

    action: {
      type: String,
      default: ''
    },

    // 绑定值
    value: {
      type: String
    },

    // 限制文件数量
    limit: {
      type: Number,
      default: 1
    },

    // 预览
    onPreview: {
      type: Function
    },

    // 上传成功
    onSuccess: {
      type: Function
    },

    // 移除
    onRemove: {
      type: Function
    },

    // 移除前提示
    beforeRemove: {
      type: Function
    },

    // 超过数量提示
    onExceed: {
      type: Function
    },

    // 多个文件路径间的分隔符
    separator: {
      type: String,
      default: '|'
    },

    // 是否允许手动输入,默认为true
    allowInput: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      urls: this.value,
      inputUrls: this.value,
      showInput: false,
      fileList: []
    }
  },
  computed: {
    actualAction () {
      return !this.action ? `${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=${this.uploadDirectory}` : this.action
    },
    actualSeparator () {
      return !this.separator ? '|' : this.separator
    },
    actualHeaders () {
      return !this.headers ? {token: this.$cookie.get('token')} : this.headers
    }
  },
  created () {
    // 防止抖动输入,频繁的无效调用
    this.rewriteToValue = this.debounce(this.rewriteToValue, 500)
  },
  activated () {

  },
  watch: {
    value (newVal, oldVal) {
      this.urls = newVal
      this.inputUrls = this.urls
      this.$refs['elUpload'].clearFiles()
      this.fileList = []
      this.urls.split(this.actualSeparator).forEach((item) => {
        if (item.trim().length > 0) {
          this.fileList.push({name: decodeURIComponent(item.substring(item.lastIndexOf('/') + 1)), url: item})
        }
      })
    }
  },
  methods: {
    defaultExceed (files, fileList) {
      this.$message.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    defaultBeforeRemove (file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    defaultRemove (file, fileList) {
      this.$http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
        this.$message.success(data.msg)
      })
      this.urls = fileList.map(item => item.url).join(this.actualSeparator)
      this.inputUrls = this.urls
      this.notify()
    },
    defaultSuccess (response, file, fileList) {
      this.urls = fileList.map(item => (item.response && item.response.url) || item.url).join(this.actualSeparator)
      this.inputUrls = this.urls
      this.notify()
    },
    defaultPreview (file, fileList) {
      this.$alert(`<img style='width:100%' src=' ${(file.response && file.response.url) || file.url}'/>`, {
        dangerouslyUseHTMLString: true,
        showConfirmButton: false,
        closeOnClickModal: true,
        customClass: 'showPic'
      })
    },
    notify () {
      // this.$emit('notify', this.urls)
      this.$emit('change', this.urls)
    },
    rewriteToValue () {
      this.urls = this.inputUrls
      this.showInput = false
      this.notify()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
